﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

using BlueCMS.Core.Data;
using BlueCMS.Core.Data.Query.Generator;

namespace BlueCMS.Providers.DataProviders.MsSql2005Provider
{
    public class DataProvider : IDataProvider
    {
        string ConnectionString;

        public DataProvider(string connectionStringName)
        {
            ConnectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
        }

        public QueryGeneratorBase GetQueryGenerator()
        {
            return new QueryGenerator();
        }

        public DbParameter CreateParameter(string name, object value)
        {
            return new SqlParameter(name, value);
        }

        public int ExecuteNonQuery(string commandText, DbParameter[] parameters)
        {
            int returnValue;
            SqlCommand command = NewCommand(commandText);
            command.Connection.Open();
            if (parameters != null)
            {
                command.Parameters.AddRange(parameters);
            }
            returnValue = command.ExecuteNonQuery();
            command.Connection.Close();

            return returnValue;
        }

        public DbDataReader ExecuteDataReader(string commandText, DbParameter[] parameters)
        {
            SqlCommand command = NewCommand(commandText);
            command.Connection.Open();
            if (parameters != null)
            {
                command.Parameters.AddRange(parameters);
            }
            return command.ExecuteReader(CommandBehavior.CloseConnection);
        }

        public object ExecuteScalar(string commandText, DbParameter[] parameters)
        {
            object returnValue;
            SqlCommand command = NewCommand(commandText);
            command.Connection.Open();
            if (parameters != null)
            {
                command.Parameters.AddRange(parameters);
            }
            returnValue = command.ExecuteScalar();
            command.Connection.Close();

            return returnValue;
        }

        protected SqlCommand NewCommand(string commandText)
        {
            return new SqlCommand(commandText, new SqlConnection(ConnectionString));
        }
    }
}
